//
//  DetailsViewController.swift
//  ShiZhe
//
//  Created by 陈卿伟 on 16/9/13.
//  Copyright © 2016年 陈卿伟. All rights reserved.
//

import UIKit
import SwiftyJSON

class DetailsViewController: MainViewController {
    var waitView:MainView!//等待视图
    var navigationLeftView:DetailBackButton!//导航左边的视图
    var navigationRightView:DetailRightView!//导航右边的视图
    var tableView:DetailTableView!//tableView
    var cell:DetailCell!
    var titleLabel:UILabel!//标题
    var model:DetailModel!
    var contentSize:CGFloat = 85*SCALEH
    
    
    
    
    
    //模拟数据
    var textTest = ["avatar":"http://v1.qzone.cc/avatar/201401/20/18/01/52dcf3e82b52a604.jpg%21200x200.jpg","userName":"x_x雪花","price":"31","title":"一个textView里面的内容高度明明比textview小，却还是会滑动的问题","text":[["text":"如果你用过网页版的百度地图，你大概3D全景图浏览是一种怎样的酷炫体验：在一个点可以360度环顾周围的建筑、景色，当然也可以四周移动，就像身临其境。"],["code":"//左边视图\nnavigationLeftView = DetailBackButton(frame: CGRect(x: 20,y: 17,width: 233*SCALEW,height: 36))\nself.navigationItem.leftBarButtonItem?.customView = navigationLeftView\nnavigationLeftView.backButton.addTarget(self, action: #selector(self.backButtonClick(_:)), forControlEvents: .TouchUpInside)\n//左边视图\nnavigationLeftView = DetailBackButton(frame: CGRect(x: 20,y: 17,width: 233*SCALEW,height: 36))\nself.navigationItem.leftBarButtonItem?.customView = navigationLeftView\nnavigationLeftView.backButton.addTarget(self, action: #selector(self.backButtonClick(_:)), forControlEvents: .TouchUpInside)"],["text_s2":"科普"],["text":"全景图共分为三种：\n\n①球面全景图\n\n利用一张全景图围成一个球，自身位置位于球体内。由于图片是矩形，所以最上和最下的缝合处很明显就能够看得出来。\n球面全景图是最接近人眼的构建模式，若利用多个立面构建，拼接方法繁琐，性能消耗高。\n因此，本文介绍的是上述通过一张全景图构成的球面全景图。\r②立方体全景图\n一个立方体，有六个面组成，所以就需要六张图片啦。自身的位置位于立方体中间。这也是最常见的全景图构建模式。\n③柱状全景图\n这个则是前两种构建模式的结合版啦。"],["image":"http://upload-images.jianshu.io/upload_images/2153376-b4c19dc21638a4ed.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"],["text_s2":"准备"],["text":"在浏览器中实现3D全景浏览开发，首先需要几样东西：\n①支持WebGL和canvas的浏览器\n②Three.js\n这里就不介绍这个插件了，所以阅读本文需要Three.js简单的基础 O(∩_∩)O~\n下载地址：https://github.com/mrdoob/three.js\n③photo-sphere-viewer.js\n这是基于Three.js开发的柱状全景图插件\n下载地址：https://github.com/JeremyHeleine/Photo-Sphere-Viewer"],["code":"var imageURL:NSURL = NSURL(string: \"http://www.szplanner.com/images/inside/product_thumb.jpg\")!\nSDWebImageManager.sharedManager().downloadImageWithURL(imageURL, options:SDWebImageOptions.allZeros, progress: { (min:Int, max:Int) -> Void in\nprintln(\"加载中 \")\n}) { (image:UIImage!, error:NSError!, cacheType:SDImageCacheType, finished:Bool, url:NSURL!) -> Void in\nif (image != nil)\n{\nprintln(\"图片缓存完成\")\n}\n}"],["image":"http://upload-images.jianshu.io/upload_images/195046-5fe838536ab65464.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"]]]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.editNavigationBarStyle()
        waitView = MainView(frame: MainBounds)
        self.view.addSubview(waitView)
        self.doAlamofire()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)
        waitView.removeFromSuperview()
        self.addTableView()
    }
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}


//MARK:--UI设置
extension DetailsViewController{
    //设置navigationBar的样式
    func editNavigationBarStyle(){
        //左边视图
        navigationLeftView = DetailBackButton(frame: CGRect(x: 20,y: 17,width: 233*SCALEW,height: 36))
        self.navigationItem.leftBarButtonItem?.customView = navigationLeftView
        navigationLeftView.backButton.addTarget(self, action: #selector(self.backButtonClick(_:)), forControlEvents: .TouchUpInside)
        
        //右边视图
        navigationRightView = DetailRightView(frame: CGRect(x: 271*SCALEW,y: 17,width: 92*SCALEW,height: 36))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: navigationRightView)
    }
    
    //添加tableView
    func addTableView(){
        self.tableView = DetailTableView(frame: CGRectMake(0, 0-30, WidthAPP, HeightAPP), style: .Grouped)
        self.view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
    }
    
    //创建body
    func createBody(cell:DetailCell,row:Int){
            let key = self.model.bodyKey[row]
            let textValue = self.model.bodyValue[row]
            switch key {
            case "text":
                let constraint = CGSizeMake(WidthAPP-30*SCALEW, 10000)
                let size = textValue.boundingRectWithSize(constraint, options: [.UsesLineFragmentOrigin,.UsesFontLeading], attributes:NSDictionary(object:UIFont(name: "Heiti SC", size: 14*SCALEW)!, forKey: NSFontAttributeName) as? [String : AnyObject],context: nil)
                let textBody = DetailTextView(frame: CGRectMake(15*SCALEW, 10*SCALEH, WidthAPP-30*SCALEW, size.height+1000*SCALEH), textContainer: nil, font: "light", size: 14)
                textBody.text = textValue
                self.tableView.rowHeight = size.height+40*SCALEH
                cell.addSubview(textBody)
            case "text_s2":
                let constraint = CGSizeMake(WidthAPP-30*SCALEW, 10000)
                let size = textValue.boundingRectWithSize(constraint, options: [.UsesLineFragmentOrigin,.UsesFontLeading], attributes:NSDictionary(object:UIFont(name: "Verdana-Bold", size: 14*SCALEW)!, forKey: NSFontAttributeName) as? [String : AnyObject],context: nil)
                let textBody = DetailTextView(frame: CGRectMake(15*SCALEW, 10*SCALEH, WidthAPP-30*SCALEW, size.height+20*SCALEH), textContainer: nil, font: "bold", size: 15)
                textBody.text = textValue
                self.tableView.rowHeight = size.height+20*SCALEH
                cell.addSubview(textBody)
            case "image":
                let imageBody = UIImageView(frame:CGRectMake(10*SCALEW, 10*SCALEH, WidthAPP-20*SCALEW, 100*SCALEH))
                let hader = BaseFunc.showPlaceHolder(imageBody)
                imageBody.sd_setImageWithURL(NSURL(string: textValue), completed: { (image, error, _, _) in
                    if error == nil{
                        let imageSize = image.size
                        var imageWidth = imageSize.width
                        var imageHeight = imageSize.height
                        let imageScale = imageWidth/imageHeight
                        if imageWidth>(WidthAPP-20*SCALEW){
                            imageWidth = WidthAPP-20*SCALEW
                            imageHeight = imageWidth/imageScale
                        }
                        imageBody.frame = CGRectMake(10*SCALEW, 10*SCALEH, imageWidth, imageHeight)
                        imageBody.center.x = WidthAPP/2
                        self.tableView.rowHeight = imageSize.height+20*SCALEH
                        hader.removeFromSuperview()
                    }
                })
                self.tableView.rowHeight = imageBody.frame.size.height+20*SCALEH
                cell.addSubview(imageBody)
            case "code":
                let constraint = CGSizeMake(10000, 10000)
                let size = textValue.boundingRectWithSize(constraint, options: [.UsesLineFragmentOrigin,.UsesFontLeading], attributes:NSDictionary(object:UIFont(name: "Heiti SC", size: 13*SCALEW)!, forKey: NSFontAttributeName) as? [String : AnyObject],context: nil)
                let codeView = DetaiCodeView(frame: CGRectMake(0,10*SCALEH,size.width,size.height+35*SCALEH))
                codeView.baseScrollView.contentSize = CGSizeMake(size.width+30*SCALEW, size.height+35*SCALEH)
                codeView.textView.text = textValue
                self.tableView.rowHeight = size.height+55*SCALEH
                cell.addSubview(codeView)
            default:
                break
        }
    }
}

//MARK:--点击事件
extension DetailsViewController{
    //返回按钮点击事件
    func backButtonClick(sender:UIButton){
        self.navigationController?.popViewControllerAnimated(true)
    }
}

//MARK:--tableView delegate  datasource
extension DetailsViewController:UITableViewDelegate,UITableViewDataSource{
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return model.bodyCount
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50*SCALEH
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 100*SCALEH
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headView = UIView(frame: CGRectMake(0,0,WidthAPP,50*SCALEH))
        titleLabel = UILabel(frame: CGRect(x: 20*SCALEW,y: 0,width: 335*SCALEW,height: 50*SCALEH))
        titleLabel.textAlignment = .Left
        titleLabel.textColor = UIColor.blackColor()
        titleLabel.font = BaseFunc.getSystemFont(17)
        titleLabel.numberOfLines = 2
        titleLabel.text = model.title
        headView.addSubview(titleLabel)
        return headView
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        cell = DetailCell(style: .Default, reuseIdentifier: "detailcell")
        createBody(cell, row: indexPath.row)
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
    }
    
}


//MARK:--Alamofire(现在是模拟)
extension DetailsViewController{
    //请求数据
    func doAlamofire(){
        dispatch_async(dispatch_queue_create("heheda", DISPATCH_QUEUE_CONCURRENT)) { 
            self.model = DetailModel(text: self.textTest)
            dispatch_async(dispatch_get_main_queue()) {
                self.navigationLeftView.avatarImage.sd_setImageWithURL(NSURL(string: self.model.avatar))
                self.navigationLeftView.userName.text = self.model.userName
                self.navigationRightView.priceNum.text = "\(self.model.price) 小肉干"
            }
        }
    }
}













